//
//  RequestAPI.m
//

//

#import "libRequestAPI.h"

@implementation libRequestAPI

@synthesize	m_Delegate;


-(id)init
{
	if( self = [super init] )
	{
		m_Downloader = [Downloader new];
	}
	return self;
}

- (id)initWith:(id)delegate
{
	if( self = [self init] )
	{
		self.m_Delegate = delegate;
	}
	return self;
}


-(void)dealloc
{
	[self requestCancel];
	[m_Downloader release];
	[m_Data release];
	[super dealloc];
}


- (BOOL)requestWith:(NSDictionary*)infodic
{
	
	NSString*	urlpath = [infodic objectForKey:kKeyRequestAPIServerURLPath];
	NSString*	body = [infodic objectForKey:kKeyRequestAPIHTMLBody];
	NSString*	Method = [infodic objectForKey:kKeyRequestAPIHTTPMethod];
	if( !urlpath ){
		return	NO;
	}
	
	NSURL*		url  = [NSURL URLWithString:urlpath];
	NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:url];
	if( Method )
		[req setHTTPMethod:Method];
	if(body)
		[req setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
	
	SAFE_RELEASE(m_Data)
	
	
	return [m_Downloader startWithRequest:req saveName:nil delegate:self];
}


- (void)requestCancel
{
	if( [m_Downloader isExec] == YES )
		[m_Downloader cancel];
}


- (BOOL)isExec
{
	return [m_Downloader isExec];
}

#pragma mark -
#pragma mark Downloader delegates


- (void)downloaderError:(NSString*)url_path
{
	if ( m_Delegate && [m_Delegate respondsToSelector:@selector(libRequestAPIDownloadError:)] )
		[m_Delegate libRequestAPIDownloadError:url_path];

}

- (void)downloaderCancel
{
	if ( m_Delegate && [m_Delegate respondsToSelector:@selector(libRequestAPIDownloadCancel)] )
		[m_Delegate libRequestAPIDownloadCancel];
}

- (void)downloaderFinish:(NSData*)data saveName:(NSString*)save_name
{
	m_Data = [data retain];
	if ( m_Delegate && [m_Delegate respondsToSelector:@selector(libRequestAPIDownloadFinish:fileName:)] )
		[m_Delegate libRequestAPIDownloadFinish:data fileName:save_name];
}

@end
